//
//  StatusCell.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/17.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit
import SDWebImage

protocol StatusCellDelegate: NSObjectProtocol {
    
    func didSelectedPhotoIndex(cell:StatusCell, index: Int)
}

class StatusCell: UITableViewCell {

    // 头像
    @IBOutlet weak var avatarImg: UIImageView!
    // 作者
    @IBOutlet weak var authorLbl: UILabel!
    // 发表时间
    @IBOutlet weak var createLbl: UILabel!
    // 来源
    @IBOutlet weak var sourceLbl: UILabel!
    // 正文
    @IBOutlet weak var contentLbl: UILabel!
    // 认证
    @IBOutlet weak var avatarEnterprise: UIImageView!
    // 等级
    @IBOutlet weak var vipLevel: UIImageView!
    
    
    // 转发信息
    @IBOutlet weak var forwardLbl: UILabel!
    
    
    // 设置图片代理
    var photoDelegate: StatusCellDelegate?

    
    // 数据模型,当赋值了之后就对控件赋值
    var status:Status? {
        didSet {
            self.avatarImg.sd_setImageWithURL(status?.user?.profile_url)
            self.authorLbl.text = status?.user?.name
            self.createLbl.text = status?.createDateStr
            self.sourceLbl.text = status?.source?.getLinkShowText()
            if status?.text != nil {
                self.contentLbl.attributedText = EmoticonsAttachment().transformStringToAttributedString(status!.text!, height: self.contentLbl.font.lineHeight)
            }
            
            self.avatarEnterprise.image = status?.user?.verifiedImg
            self.vipLevel.image = status?.user?.vipImg
            
            //  计算布局
            let vf = self.calaImageFrame(status!)
            self.imageCollectionHeight.constant = vf.viewSize.height
            self.imageCollectionWidth.constant = vf.viewSize.width
            self.layoutImage.itemSize = vf.itemSize
            
            // 转发微博
            if status?.retweeted_status != nil {
                let str = (status?.retweeted_status?.user?.name ?? "") + ":" + (status?.retweeted_status?.text ?? "")
                forwardLbl.text = str
            }
            self.imageCollection.reloadData()
        }
    }

    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentLbl.numberOfLines = 0
        self.contentLbl.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 30
        self.forwardLbl?.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 50
    }

    
    // 根据图片多少大小,计算位置
    private func calaImageFrame(statusfunc:Status) -> (viewSize:CGSize, itemSize:CGSize){
        let itemSize = CGSizeMake(90, 90)
        let margin:CGFloat = 10
        let rowCount: Int = 3
        
        
        if statusfunc.pictureURLs == nil {
            return (CGSizeZero, itemSize)
        }
        
        // 没有图片,item不要返回(0,0)
        if  statusfunc.pictureURLs?.count == 0 {
            return (CGSizeZero, itemSize)
        }
        
        // 一张图片时候,获取原图的大小,当大于最大的时候使用
        if statusfunc.pictureURLs?.count == 1 {
            // 从缓存中获取图片
            let key = statusfunc.pictureURLs?[0].absoluteString
            let size = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key).size
            return (size, size)
        }
        
        // 4张图片
        if statusfunc.pictureURLs?.count == 4 {
            let viewSize = CGSizeMake(itemSize.width * 2 + margin, itemSize.height * 2 + margin)
            return (viewSize,itemSize)
        }
        
        // 其他图片
        let col = (statusfunc.pictureURLs!.count - 1) / 3 + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(col) + margin * CGFloat(col - 1)
        let viewSize = CGSizeMake(w, h)
        
        return (viewSize, itemSize)
    }
    
    
    
    // 微博的图片视图
    @IBOutlet weak var imageCollection: UICollectionView!
    // 约束高
    @IBOutlet weak var imageCollectionHeight: NSLayoutConstraint!
    // 约束宽
    @IBOutlet weak var imageCollectionWidth: NSLayoutConstraint!

    @IBOutlet weak var layoutImage: UICollectionViewFlowLayout!
    // 选择视图
    @IBOutlet weak var optionView: UIView!
    
    
    // 根据最后一个选择视图,获取高度
    func getRowHeight(status:Status) -> CGFloat {
        self.status = status
        self.layoutIfNeeded()
        return CGRectGetMaxY(optionView.frame)
        
    }
    
    // 获取cell 的类型
    class func cellType(status:Status) -> String{
        var type = "StatusCell"
        if status.retweeted_status != nil {
            type = "ForwardCell"
        }
        return type
        
    }
    
    
}

extension StatusCell: UICollectionViewDataSource, UICollectionViewDelegate {
    
    // 每条微博的图片
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.status?.pictureURLs?.count ?? 0
    }
    
    
    // 图片视图
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as! StatusImageCell
        cell.url = self.status!.pictureURLs![indexPath.item]
        return cell
    }
    
    
    // 选中事件
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 传入数据
        photoDelegate?.didSelectedPhotoIndex(self, index: indexPath.item)
    }
    
}


class StatusImageCell: UICollectionViewCell {
    // 文件
    @IBOutlet weak var iconView: UIImageView!
    
    var url:NSURL? {
        didSet {
            iconView.sd_setImageWithURL(url)
            self.iconView.userInteractionEnabled = true
        }
    }
    
}


















